<template>
  <div class="app-container">
    <div style="padding:20px;">
      <el-form
        ref="form"
        :model="searchForm"
        :inline="true"
        class="search-form"
      >
       <div class="flex-between">
         <div style="flex:1">
            <el-form-item label="关键字">
              <el-input
                v-model="searchForm.keywords"
                placeholder="活动ID，活动名称"
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="searchForm.status"
                style="width: 100%"
                placeholder="活动状态"
                clearable
              >
                <el-option
                  v-for="item in activityStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
         </div>
        <div class="button-box">
            <el-form-item>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-search"
                @click="doSearchList"
                >查询</el-button
              >
              <el-button
                size="small"
                type="primary"
                icon="el-icon-refresh"
                @click="doCancelSearch"
                >重置</el-button
              >
            </el-form-item>
         </div>
         </div>
      </el-form>
    </div>
    <el-divider></el-divider>
    <div class=" marginTop">
      <div class="marginBottom">
        <el-row :gutter="20">
          <el-col>
            <el-button
              icon="el-icon-circle-plus-outline"
              type="primary"
              size="small"
              @click="goAddSeckillActivity"
              >添加活动</el-button
            >
          </el-col>
        </el-row>
      </div>
      <el-row :gutter="20">
        <el-col>
          <el-table
            v-loading="isLoading"
            :header-cell-style="{
              'background-color': '#f3f8fe',
              color: '#606266',
              height: '50px',
            }"
            highlight-current-row
            :data="seckillList"
            style="width: 100%"
          >
            <el-table-column
              prop="id"
              label="ID"
              width="80"
              align="center"
            />
            <el-table-column
              prop="activity_name"
              label="活动名称"
              align="center"
              width="250"
            >
            <template slot-scope="scope">
               <el-tooltip placement="top-start" :content="scope.row.activity_name + ''">
                 <div class="one_line_hidden">
                   {{ scope.row.activity_name ? scope.row.activity_name : "-" }}
                 </div>
               </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column
              prop="seckill_count"
              label="数量"
              width="100"
              align="center"
            />
            <el-table-column label="状态" width="100" align="center">
              <template slot-scope="scope">
                <!-- 活动状态:-1结束 1开启 2关闭 3进行中 -->
                <span v-if="scope.row.status == -1" style="color:#ff4949;"
                  >已结束</span
                >
                <span
                  v-else-if="scope.row.status == 1" style="color:#13ce66;"
                  >已开启</span
                >
                <span
                  v-else-if="scope.row.status == 2" style="color:#81b337;"
                  >已关闭</span
                >
                <span v-else-if="scope.row.status == 3" style="color:#13ce66;"
                  >进行中</span
                >
              </template>
            </el-table-column>
            <el-table-column
              prop="start_time"
              label="开始时间"
              width="180"
              align="center"
            />
            <el-table-column
              prop="end_time"
              label="结束时间"
              width="180"
              align="center"
            />
            <el-table-column
              prop="created_at"
              label="创建时间"
              width="180"
              align="center"
            />
            <el-table-column
              prop="updated_at"
              label="更新时间"
              align="center"
            >
            <template slot-scope="scope">
               <el-tooltip placement="top-start" :content="scope.row.updated_at + ''">
                 <div class="one_line_hidden">
                   {{ scope.row.updated_at ? scope.row.updated_at : "-" }}
                 </div>
               </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="200"
              align="center"
            >
              <template slot-scope="scope">
                <span v-hasPermi="'seckill/toggle'" style="margin-right: 10px">
                  <el-button
                    v-if="scope.row.status == 1 || scope.row.status == 3"
                    type="warning"
                    size="mini"
                    @click="toggleActivityStatus(scope.row.id)"
                  >
                    关闭活动
                  </el-button>
                  <el-button
                  disabled
                    style="margin: 5px"
                    v-if="scope.row.status == -1"
                    type="danger"
                    size="mini"
                  >
                    活动结束
                  </el-button>
                  <el-button
                    v-else-if="scope.row.status == 2"
                    type="success"
                    size="mini"
                    @click="toggleActivityStatus(scope.row.id)"
                  >
                    开启活动
                  </el-button>
                </span>
                <el-button
                  v-hasPermi="'seckill/update'"
                  style="margin-right: 10px"
                  type="primary"
                  size="mini"
                  :disabled="scope.row.status == 1 || scope.row.status == 3"
                  @click="goEditSeckillActivity(scope.row.id)"
                  >修改</el-button
                >
                <el-popconfirm
                  title="确定删除吗？"
                  @confirm="doDeleteActivity(scope.row.id)"
                >
                  <el-button
                    slot="reference"
                    v-hasPermi="'seckill/del'"
                    :disabled="scope.row.status == 1 || scope.row.status == 3"
                    type="danger"
                    size="mini"
                  >
                    删除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row class="marginTop" style="text-align: right">
        <el-pagination
          style="margin-top: 10px"
          :current-page.sync="paginationObj.start"
          :page-sizes="paginationObj.pageSizes"
          :page-size="paginationObj.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paginationObj.total"
          background
          @size-change="sizeChange"
          @current-change="currentChange"
        />
      </el-row>
    </div>
    <!-- 新增或者编辑 -->
    <el-drawer :modal-append-to-body="false" :append-to-body="true" :title="seckillId ? '修改活动' : '添加活动'" size="70%" :withHeader="false"
      :visible.sync="dialogVisible" @close="handleClose" :show-close="true">
      <div style="position: relative">
        <div class="drawerTitle">
          <span>{{seckillId ? '修改活动' : '添加活动'}}</span>
          <div class="close" @click="handleClose">
            <i class="el-icon-close" style="font-size: 24px;"></i>
          </div>
        </div>
      </div>
       <el-scrollbar wrap-style="overflow-x:hidden;" style="height: calc(100vh - 150px)">
      <el-row v-loading="submitLoading" style="margin:6px 0 0 10px;">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
        <el-col :span="24">
        <div class="informationTitleView">
          <div class="leftBox" style="padding-left: 10px;">
            <div class="leftborder"></div>
            <div class="text">基本信息</div>
          </div>
          <div class="right"></div>
        </div>
        </el-col>
          <el-col :span="8">
            <el-form-item label="活动名称" prop="activity_name">
              <el-input
                v-model="ruleForm.activity_name"
                placeholder="请输入活动名称"
                :maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="活动时间" prop="startEndTime">
              <el-date-picker
                v-model="ruleForm.startEndTime"
                style="width: 100%"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="ruleForm.status">
                <el-radio :label="1">开启</el-radio>
                <el-radio :label="2">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="省市区" prop="address">
              <el-cascader
                v-model="ruleForm.address"
                style="width: 100%"
                :options="addressList"
                collapse-tags
                :props="{
                  multiple: true,
                  value: 'id',
                  label: 'name',
                  children: 'children',
                  checkStrictly: true,
                }"
                clearable
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="22">
            <el-form-item label="活动轮播">
              <logo-upload
                :file-list="ruleForm.carousel"
                :show-file-list="true"
                accept="image/jpeg, image/png"
                @uploadCallback="carouselBack"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="10" :offset="0">
            <el-form-item label="主图" prop="imageUrl">
              <logo-upload
                :single-file="ruleForm.imageUrl"
                :show-file-list="false"
                accept="image/jpeg, image/png"

                @uploadCallback="baseFormMainImageSucc"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
          <div class="informationTitleView" style="margin-top: 0px;">
            <div class="leftBox" style="padding-left: 10px;">
              <div class="leftborder"></div>
              <div class="text">扩展信息</div>
            </div>
            <div class="right"></div>
          </div>
          </el-col>
          <el-col :span="22">
            <el-form-item label="用户相关">
              <el-button type="primary" size="small" @click="showDrawer('user')"
                >指定用户</el-button
              >
              <el-button
                type="primary"
                size="small"
                @click="showDrawer('user-group')"
                >指定用户分组</el-button
              >
              <el-button
                type="primary"
                size="small"
                @click="showDrawer('user-label')"
                >指定用户标签</el-button
              >
              <div
                v-if="choosedUserList.length > 0"
                style="margin: 10px 0;"
              >
                <span>已选用户：</span>
                <el-tag
                  v-for="user in choosedUserList"
                  :key="user.id"
                  style="margin-right: 10px"
                  type="success"
                  size="mini"
                  effect="dark"
                  >{{ user.nickname }}</el-tag
                >
              </div>
              <div
                v-if="choosedUserGroupList.length > 0"
                style="margin-bottom: 10px"
              >
                <span>已选用户分组：</span>
                <el-tag
                  v-for="group in choosedUserGroupList"
                  :key="group.id"
                  style="margin-right: 10px"
                  type="primary"
                  size="mini"
                  effect="dark"
                  >{{ group.name }}</el-tag
                >
              </div>
              <div
                v-if="choosedUserLabelList.length > 0"
                style="margin-bottom: 10px"
              >
                <span>已选用户标签：</span>
                <el-tag
                  v-for="label in choosedUserLabelList"
                  :key="label.id"
                  style="margin-right: 10px"
                  type="warning"
                  size="mini"
                  effect="dark"
                  >{{ label.tag_name }}</el-tag
                >
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="22">
            <el-form-item label="参与商品" prop="chooseSkuList">
              <el-select
                v-model="tempChoosedGoods"
                style="width: 400px"
                :multiple="false"
                filterable
                remote
                reserve-keyword
                placeholder="关键字查询支持商品名、ID、副标题、编码"
                :remote-method="getGoodsListWay"
                :loading="isLoadingGoods"
                value-key="id"
                @change="handleChooseGoodsChange"
              >
                <el-option
                  v-for="item in GoodsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <div v-if="skuList.length > 0 || confirmGoodsSkuList.length > 0" style="margin-left:10px;">
              <el-tabs
                v-model="activeChooseGoodsName"
                @tab-click="handleChoooseGoodsClick"
              >
                <el-tab-pane
                  v-if="skuList.length > 0"
                  label="填写商品规格"
                  name="goChooseGoods"
                >
                  <div>
                    <choosed-seckill-sku-comp
                      ref="chooseSeckillSkuRef"
                      :display="false"
                      :list="skuList"
                      @updatelist="handleCurrentChooseGoods"
                      @deleteitem="handleDeleteItem"
                    />
                  </div>
                </el-tab-pane>
                <el-tab-pane
                  v-if="confirmGoodsSkuList.length > 0"
                  :label="'已确定商品规格(' + confirmGoodsSkuList.length + ')'"
                  name="choosedList"
                >
                  <choosed-seckill-sku-comp
                    ref="displayChooseSeckillSkuRef"
                    :is-update="seckillId ? true : false"
                    display
                    :list="confirmGoodsSkuList"
                    @updatelist="handleUpdateList"
                    @deleteitem="handleDeleteItem"
                  />
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-col>
        </el-form>
      </el-row>
      </el-scrollbar>
      <div>
        <el-row style="margin: 20px 0">
          <el-col :span="24" style="text-align: right; padding-right: 30px;">
            <el-button @click="doCancel">取消</el-button>
            <el-button :loading="submitLoading" type="primary" @click="doSubmit">保存</el-button>
          </el-col>
        </el-row>
      </div>
    </el-drawer>

    <el-drawer :modal-append-to-body="false" :append-to-body="true" title="指定用户信息" size="60%" :withHeader="false"
      :visible.sync="isShowDrawer" @close="handleCloseDrawer" :show-close="true">
      <div style="position: relative">
        <div class="drawerTitle">
          <span>指定用户信息</span>
          <div class="close" @click="handleCloseDrawer">
            <i class="el-icon-close" style="font-size: 24px;"></i>
          </div>
        </div>
      </div>
      <div style="padding: 20px 30px 0">
        <div v-if="choosedUserList.length > 0" style="margin-bottom: 10px">
          <span style="color:#0076f6;">已选用户：</span>
          <el-tag
            v-for="user in choosedUserList"
            :key="user.id"
            style="margin-right: 10px"
            type="success"
            size="mini"
            effect="dark"
            >{{ user.nickname }}</el-tag
          >
        </div>
        <div v-if="choosedUserGroupList.length > 0" style="margin-bottom: 10px">
          <span style="color:#0076f6;">已选用户分组：</span>
          <el-tag
            v-for="group in choosedUserGroupList"
            :key="group.id"
            style="margin-right: 10px"
            type="primary"
            size="mini"
            effect="dark"
            >{{ group.name }}</el-tag
          >
        </div>
        <div v-if="choosedUserLabelList.length > 0" style="margin-bottom: 10px">
          <span style="color:#0076f6;">已选用户标签：</span>
          <el-tag
            v-for="label in choosedUserLabelList"
            :key="label.id"
            style="margin-right: 10px"
            type="warning"
            size="mini"
            effect="dark"
            >{{ label.tag_name }}</el-tag
          >
        </div>

        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="指定用户" name="user">
            <user-list-comp
              ref="userListRef"
              @userchoosechange="handleChoosedUserChange"
            />
          </el-tab-pane>
          <el-tab-pane label="指定用户分组" name="user-group">
            <user-group-comp
              ref="userGroupRef"
              @usergruopchange="handleUserGroupChange"
            />
          </el-tab-pane>
          <el-tab-pane label="指定用户标签" name="user-label">
            <user-label-comp
              ref="userLabelRef"
              @userlabelchange="handleUserLabelChange"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import mix from "@/mixins/index";
import LogoUpload from "@/components/FileUpload";
import UserListComp from "./components/UserList.vue";
import UserGroupComp from "./components/UserGroup.vue";
import UserLabelComp from "./components/UserLabel.vue";
import ChoosedSeckillSkuComp from "./components/ChoosedSeckillSku.vue";
import { parseTime } from "@/utils/index";
import { getRegionList } from "@/api/user/index";
import {
  list,
  del,
  changeStatus,
  add,
  detail,
  edit,
  getGoodsList as getGoodsListApi,
} from "@/api/activity/index";

export default {
  name: "Seckill",
  components: {
    LogoUpload,
    UserListComp,
    UserGroupComp,
    UserLabelComp,
    ChoosedSeckillSkuComp,
  },
  mixins: [mix],
  data() {
    const mainImageValidator = (rule, value, callback) => {
      if (this.ruleForm.imageUrl.url === "") {
        callback(new Error("请上传商品主图"));
      } else {
        callback();
      }
    };
    const choosedSeckillSkuListValidator = (rule, value, callback) => {
      if (this.ruleForm.chooseSkuList.length === 0) {
        callback(new Error("至少选择一个商品"));
      } else {
        callback();
      }
    };
    return {
      isLoading: false,
      searchForm: {},
      seckillList: [], // 秒杀活动列表
      activityStatusList: [
        {
          label: "结束",
          value: -1,
        },
        {
          label: "开启",
          value: 1,
        },
        {
          label: "关闭",
          value: 2,
        },
        {
          label: "进行中",
          value: 3,
        },
      ],
      // 新增或编辑相关
      seckillId: "", // 要修改的秒杀互动ID
      title: "新增活动",
      dialogVisible: false,
      submitLoading: false,
      isLoadingDetail: false,
      rules: {
        activity_name: [
          {
            required: true,
            validator: (rul, value, callback) => {
              let req = /[^a-zA-Z0-9\u4e00-\u9fa5]/g;
              console.log(req.test(value));
              if (req.test(value)) {
                callback(new Error("名称中不能包含特殊字符"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        status: [{ required: true, message: "活动状态必填", trigger: "blur" }],
        startEndTime: [
          { required: true, message: "开始结束时间必填", trigger: "blur" },
        ],
        imageUrl: [
          { required: true, validator: mainImageValidator, trigger: "blur" },
        ],
        chooseSkuList: [
          {
            required: true,
            validator: choosedSeckillSkuListValidator,
            trigger: "blur",
          },
        ],
      },
      ruleForm: {
        activity_name: "",
        status: "",
        startEndTime: [],
        address: [],
        imageUrl: {}, // 主图url
        carousel: [], // 轮播图
        chooseSkuList: [], // 选中的秒杀商品规格列表
      },
      addressList: [], // 省市区
      isShowDrawer: false,
      activeName: "user", // user , user-group,user-label
      choosedUserList: [], // 选中的用户
      choosedUserGroupList: [], // 选中的用户分组
      choosedUserLabelList: [], // 选中的用户标签
      isShowGoodsDrawer: false,
      choosedSeckillList: [], // 选中的秒杀商品
      // 选择商品
      searchGoodsForm: {
        startEndTime: [],
      },
      searchGoodsFormRules: {
        startEndTime: [
          { required: true, message: "时间段必选", trigger: "blur" },
        ],
      },
      activeChooseGoodsName: "goChooseGoods", // goChooseGoods  choosedList
      isLoadingGoods: false,
      GoodsList: [], // 搜索出来的商品列表
      tempChoosedGoods: {},
      skuList: [],
      confirmGoodsSkuList: [], // 确定的秒杀商品列表
    };
  },

  created() {
    this.getSeckillList();
    this.getRegionListData();
  },
  methods: {
    // ********************活动列表********************
    // 获取秒杀活动列表
    async getSeckillList() {
      this.isLoading = true;
      this.searchForm.page = this.paginationObj.start;
      this.searchForm.count = this.paginationObj.limit;
      const res = await list(this.searchForm);
      const { code, data, msg } = res;
      if (code === 200) {
        this.seckillList = data.list;
        this.paginationObj.total = data.total;
      } else {
        this.$message.error(msg);
      }
      this.isLoading = false;
    },

    doSearchList() {
      this.paginationObj.start = 1;
      this.getSeckillList();
    },
    doCancelSearch() {
      this.searchForm = this.$options.data().searchForm;
      this.getSeckillList();
    },

    sizeChange(val) {
      this.paginationObj.limit = val;
      this.paginationObj.start = 1;
      this.getSeckillList();
    },
    currentChange(val) {
      this.paginationObj.start = val;
      this.getSeckillList();
    },
    async doDeleteActivity(id) {
      const res = await del({ id });
      const { code, msg } = res;
      if (code === 200) {
        this.$message.success("删除成功！");
        this.getSeckillList();
      } else {
        this.$message.error(msg);
      }
    },
    goAddSeckillActivity() {
      // this.$router.push('/activity/seckill/add')
      this.dialogVisible = true;
    },
    goEditSeckillActivity(id) {
      // this.$router.push({ path: '/activity/seckill/add', query: { id }})
      this.dialogVisible = true;
      this.seckillId = id;
      this.activeChooseGoodsName = "choosedList";
      this.getSeckillActivityDetail();
    },
    // 开启或者关闭活动
    toggleActivityStatus(id) {
      this.isLoading = true;
      changeStatus({
        action: "seckill",
        id,
      })
        .then((res) => {
          const { code, msg } = res;
          if (code === 200) {
            this.$message.success("状态修改成功！");
            this.getSeckillList();
          } else {
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          console.log("err=>", err);
        });
    },

    // 删除已经选中的秒杀商品
    handleDeleteItem(row) {
      this.isLoading = true;
      if (row.product_id) {
        this.confirmGoodsSkuList = this.confirmGoodsSkuList.filter(
          (item) => item.product_id !== row.product_id
        );
        this.skuList = this.skuList.filter(
          (item) => item.id !== row.product_id
        );
      } else {
        this.confirmGoodsSkuList = this.confirmGoodsSkuList.filter((item) => {
          if (item.product_id) {
            return item.product_id !== row.id;
          } else {
            return item.id !== row.id;
          }
        });
        this.skuList = this.skuList.filter((item) => item.id !== row.id);
      }

      this.$refs.displayChooseSeckillSkuRef.refreshList(
        this.confirmGoodsSkuList
      );
      this.$nextTick(() => {
        if (this.$refs.chooseSeckillSkuRef) {
          this.$refs.chooseSeckillSkuRef.refreshList(this.skuList);
        }
      });

      if (this.confirmGoodsSkuList.length === 0) {
        this.activeChooseGoodsName = "goChooseGoods";
      }
    },

    // ********************新增或者编辑********************

    // 获取活动详情
    async getSeckillActivityDetail() {
      this.isLoadingDetail = true;
      const res = await detail({ id: this.seckillId });
      const { code, data, msg } = res;
      if (code === 200) {
        this.ruleForm.activity_name = data.activity_name;
        this.ruleForm.startEndTime = [
          new Date(data.start_time),
          new Date(data.end_time),
        ];
        try {
          this.ruleForm.address = JSON.parse(data.cover_region_json);
          this.ruleForm.imageUrl = { url: JSON.parse(data.image).url };
          this.ruleForm.image = JSON.parse(data.image);
          this.ruleForm.carousel = JSON.parse(data.images).map((item) => ({
            url: item.url,
          }));
        } catch (error) {
          console.log("error==>", error);
        }

        this.ruleForm.status = data.status;
        // 回显数据
        this.redisplayData(data);
      } else {
        this.$message.error(msg);
      }
      this.isLoadingDetail = false;
    },
    // 回显数据
    redisplayData(data) {
      if (data.cover_user) {
        const coverUserIdArr = data.cover_user.split(",");
        const coverUserNameArr = data.cover_user_name.split(",");
        coverUserIdArr.forEach((item, index) => {
          this.choosedUserList.push({
            id: item,
            nickname: coverUserNameArr[index],
          });
        });
      }

      if (data.cover_group) {
        const coverGroupIdArr = data.cover_group.split(",");
        const coverGroupNameArr = data.cover_group_name.split(",");
        coverGroupIdArr.forEach((item, index) => {
          this.choosedUserGroupList.push({
            id: item,
            name: coverGroupNameArr[index],
          });
        });
      }
      if (data.cover_label) {
        const coverLabelIdArr = data.cover_label.split(",");
        const coverLabelNameArr = data.cover_label_name.split(",");

        coverLabelIdArr.forEach((item, index) => {
          this.choosedUserLabelList.push({
            id: item,
            tag_name: coverLabelNameArr[index],
          });
        });
      }
      data.seckill.forEach((item) => {
        item.inventory1 = Number(item.inventory);
        item.currentInventory = Number(item.detail.inventory);
        item.currentRetail_price = Number(item.detail.retail_price);
        this.$set(item, "isConfirm", false);
        this.$set(item, "isUpdate", false);
        this.$set(item, "detail", item.detail);
        this.$set(item, "currentInventory", item.detail.inventory);
      });
      this.confirmGoodsSkuList = data.seckill;
    },

    // 获取城市信息
    async getRegionListData() {
      const res = await getRegionList();
      const { code, data, message } = res;
      if (code === 200) {
        this.addressList = data;
      } else {
        this.$message.error(message);
      }
    },
    // 轮播图上传成功的回调
    carouselBack(res) {
      this.ruleForm.carousel = res;
    },
    // 主图上传成功
    baseFormMainImageSucc(res) {
      this.ruleForm.imageUrl = res;
      this.ruleForm.image = {
        url: res.url,
        link_url: "",
      };
    },
    // 关闭对话框
    handleClose() {
      this.ruleForm = this.$options.data().ruleForm;
      this.resetRuleForm();
      this.dialogVisible = false
    },
    doCancel() {
      this.dialogVisible = false;
      this.handleClose();
    },
    resetRuleForm() {
      this.ruleForm = this.$options.data().ruleForm;
      this.choosedUserList = [];
      this.choosedUserLabelList = [];
      this.choosedUserGroupList = [];
      this.ruleForm.chooseSkuList = [];
      this.confirmGoodsSkuList = [];
      this.seckillId = "";
    },
    doSubmit() {
      this.ruleForm.chooseSkuList = [];
      this.confirmGoodsSkuList.forEach((item) => {
        const newItem = {
          goods_id: item.goods_id,
          price: Number(item.price),
          num: Number(item.num),
          postage: item.postage,
          inventory: Number(item.inventory1),
        };
        if (item.product_id) {
          newItem.id = item.id;
          newItem.product_id = item.product_id;
        } else {
          newItem.product_id = item.id;
        }
        this.ruleForm.chooseSkuList.push(newItem);
      });
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          console.log("this.ruleForm=>", this.ruleForm);
          // 开始规整数据
          this.submitLoading = true;
          const paramsObj = {
            status: this.ruleForm.status,
            activity_name: this.ruleForm.activity_name,
            image: JSON.stringify(this.ruleForm.image),
            start_time: parseTime(this.ruleForm.startEndTime[0]),
            end_time: parseTime(this.ruleForm.startEndTime[1]),
            images: JSON.stringify(
              this.ruleForm.carousel.map((item) => ({
                url: item.url,
                link_url: "",
              }))
            ),
            cover_region_json: JSON.stringify(this.ruleForm.address),
            cover_user: this.choosedUserList.map((item) => item.id).join(","),
            cover_label: this.choosedUserLabelList
              .map((item) => item.id)
              .join(","),
            cover_group: this.choosedUserGroupList
              .map((item) => item.id)
              .join(","),
            seckill: this.ruleForm.chooseSkuList,
          };
          let api = add;
          if (this.seckillId) {
            paramsObj.id = this.seckillId;
            api = edit;
          } else {
            api = add;
          }
          console.log("paramsObj===>", paramsObj);
          const res = await api(paramsObj);
          this.submitLoading = false;
          const { code, msg } = res;
          this.dialogVisible = false;
          if (code === 200) {
            this.$message.success(
              this.seckillId ? "秒杀活动修改成功！" : "秒杀活动添加成功！"
            );
            this.getSeckillList();
            this.resetRuleForm();
          } else {
            this.$message.error(msg);
            this.resetRuleForm();
          }
        } else {
          this.$message.error("请检查：有部分信息或图片尚未添加完整！");
        }
      });
    },
    showDrawer(flag) {
      this.isShowDrawer = true;
      this.activeName = flag;
      this.redisplayTableData(true);
    },
    // 表格回显
    redisplayTableData() {
      // 回显数据user , user-group,user-label
      if (this.seckillId && this.activeName === "user") {
        this.$nextTick(() => {
          this.$refs.userListRef.redisplayUser(this.choosedUserList);
        });
      } else if (this.seckillId && this.activeName === "user-group") {
        this.$nextTick(() => {
          this.$refs.userGroupRef.redisplayUser(this.choosedUserGroupList);
        });
      } else if (this.seckillId && this.activeName === "user-label") {
        this.$nextTick(() => {
          this.$refs.userLabelRef.redisplayUser(this.choosedUserLabelList);
        });
      }
    },
    // 关闭抽屉
    handleCloseDrawer() {
      this.isShowDrawer = false;
      // 重置表格数据
      this.$refs.chooseSeckillSkuRef.resetData();
      this.$refs.displayChooseSeckillSkuRef.resetData();
    },
    handleClick(val) {
      this.activeName = val.name;
      this.redisplayTableData();
    },
    handleChoosedUserChange(val) {
      this.choosedUserList = val;
    },
    handleUserGroupChange(val) {
      this.choosedUserGroupList = val;
    },
    handleUserLabelChange(val) {
      this.choosedUserLabelList = val;
    },
    goChooseGoods() {
      this.isShowGoodsDrawer = true;
    },

    // 处理选择商品规格相关
    handleChoooseGoodsClick(val) {
      if (val === "choosedList") {
        this.skuList = [];
        this.$refs.chooseSeckillSkuRef.refreshList(this.skuList);
      }
      this.activeChooseGoodsName = val.name;
    },
    // 获取商品列表
    getGoodsListWay(query) {
      if (query !== "") {
        this.isLoadingGoods = true;
        getGoodsListApi({
          keywords: query,
          action: "seckill",
          start_time: parseTime(this.ruleForm.startEndTime[0]),
          end_time: parseTime(this.ruleForm.startEndTime[1]),
        })
          .then((res) => {
            this.isLoadingGoods = false;
            this.GoodsList = res.data.list;
            this.total = res.data.total;
          })
          .catch(() => {
            this.isLoadingGoods = false;
          });
      } else {
        this.GoodsList = [];
      }
    },

    // 接收更新的数据
    handleUpdateList(row) {
      if (row.product_id) {
        let item = this.confirmGoodsSkuList.find(
          (item) => item.product_id === row.product_id
        );
        if (item) {
          item = row;
        }
      } else {
        const list = this.confirmGoodsSkuList.filter(
          (item) => !item.product_id
        );
        if (list.length > 0) {
          let item = list.find((item) => item.id === row.id);
          if (item) {
            item = row;
          }
        }
      }
    },
    // 选择的商品改变
    handleChooseGoodsChange(val) {
      val.product.forEach((item) => {
        this.$set(item, "isConfirm", false);
        this.$set(item, "isUpdate", true);
        this.$set(item, "detail", val);
        this.$set(item, "currentInventory", item.inventory);
      });
      this.skuList = val.product;
      this.$nextTick(() => {
        this.$refs.chooseSeckillSkuRef.refreshList(this.skuList);
      });
    },
    handleCurrentChooseGoods(row) {
      const item = this.confirmGoodsSkuList.find((item) => item.id === row.id);
      if (item) {
        this.$message.warning("该商品已经选择过了！");
        return;
      }
      this.confirmGoodsSkuList.push(row);
    },
  },
};
</script>
<style lang='scss' scoped>
.splitTitle {
  font-size: 16px;
  font-weight: 700;
  color: #606266;

  .split {
    width: 95%;
    border-bottom: 2px solid #c9c9c980;
    padding-bottom: 10px;
    margin: 20px auto;
  }
}
</style>
<style>
.el-upload--picture-card {
  width: 90px !important;
  height: 90px !important;
  line-height: 90px;
}

.el-upload-list--picture-card .el-upload-list__item-actions {
  width: 90px !important;
  height: 90px !important;
}

.el-upload-list--picture-card .el-upload-list__item-thumbnail {
  width: 90px !important;
  height: 90px !important;
}

.el-upload-list--picture-card .el-upload-list__item {
  width: 90px !important;
  height: 90px !important;
}

.tox .tox-dialog-wrap__backdrop {
  z-index: 9993 !important;
}

.tox-tinymce-aux {
  z-index: 9990 !important;
}

.tox .tox-dialog {
  z-index: 9995 !important;
}
</style>
